<?php
namespace Admin\Frontend\Controllers;

use Helpers\Assets;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Admin\Models\stats\XhstatsWelfare;

class StatsWelfareController extends ControllerBase
{

    const powerTag = 'Ask_Welfare';
    private $welfareEnum = [
        1 => [
            'bQuit'      => [0 => '参加', 1 => '<font color="red">放弃</font>'],
            'sExtraVal1' => [1 => '初一', 2 => '初二'],
            'sExtraVal2' => [1 => '第一期', 2 => '第二期'],
        ]
    ];

    //检查权限
    private function checkPower($power = '', $prefix = '')
    {
        $power and $power = '_' . ucfirst($power);
        $prefix or $prefix = self::powerTag;
        return UserPower::checkUserPower($prefix . $power);
    }

    /**
     * 报名列表
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180209
     */
    public function indexAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/stats_welfare/index.js');

        $type = $this->request->getQuery('type', 'int');
        if (!$type) {
            return $this->sendViewError('参数错误');
        }
        if (!$this->checkPower()) {
            return $this->sendViewError('无查看权限');
        }
        $listSearchArr = $listButtonArr = [];
        if ($this->checkPower('del')) {
            $listButtonArr[] = ['id'=>'bt_list_del', 'text'=>'删除', 'icon'=>'fa-trash'];
        }
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_quit', 'data' => ['' => '-状态-', 0 => '参加', 1 => '放弃']];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague', 'label' => ' 搜索：'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_school', 'label' => ' 学校：'];
        return $this->view->setVars([
            'List' => Template::createList('list', 'Stats_Welfare_' . $type, [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ])
        ]);
    }

    /**
     * 获取报名学生列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180209
     */
    public function getWelfareAction()
    {
        $type   = $this->request->getPost('type', 'int');
        $school = $this->request->getPost('school', 'string');
        $quit   = $this->request->getPost('quit', 'int');
        if (!$type) {
            return $this->sendDataGridError(400, '缺少报名类型');
        }
        try {
            $builder = $this->modelsManager->createBuilder()
                ->columns(['w.iSWId', 'w.iUserId', 'u.sLogonName', 'u.sUserName', 'u.iSchoolId', 's.sSchoolName', 'w.bQuit', 'w.sPhoneNum', 'w.sExtraVal1', 'w.sExtraVal2'])
                ->from(['w' => '\\Admin\\Models\\stats\\XhstatsWelfare'])
                ->leftJoin('\\Admin\\Models\\user\\XhsysUser', 'w.iUserId = u.iUserId', 'u')
                ->leftJoin('\\Admin\\Models\\school\\XhschoolInfo', 'u.iSchoolId = s.iSchoolId', 's')
                ->where('w.bDelete = 0 AND w.iType = :type:', ['type' => $type])
                ->orderBy('w.iSwId desc');
            if ($school) {
                $builder->andWhere('s.sSchoolName like :schoolName:', ['schoolName' => '%' . $school . '%']);
            }
            if ($quit !== null && $quit !== '') {
                $builder->andWhere('w.bQuit = :quit:', ['quit' => $quit]);
            }

            //添加学校权限
            $schoolIds = User::getSchoolPower(false, null, true);
            if ($schoolIds === false) {
                return $this->sendDataGridError(400, '无学校权限');
            }
            elseif (is_array($schoolIds)) {
                $builder->andWhere('u.iSchoolId IN ({schoolIds:array})', ['schoolIds' => $schoolIds]);
            }

            $conditions = '';
            Main::runSearchVagueConditions($conditions, ['u.iUserId', 'u.sLogonName', 'u.sUserName', 'w.sPhoneNum']);
            if ($conditions) {
                $builder->andWhere($conditions);
            }
            $data = Main::runBuilderPage($builder, $this->welfareEnum[$type]);
            return $this->sendJsonResponse($data);
        }
        catch (\Exception $e) {
            return $this->sendDataGridError(500, $e->getMessage());
        }
    }

    /**
     * 删除学生报名
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180209
     */
    public function delWelfareAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        if (!XhstatsWelfare::deleteRecord('iSWId', $ids)) {
            return $this->sendErrorResponse(500, '删除失败');
        }
        return $this->sendSuccessResponse('删除成功');
    }


}